<template>
  <div>
    <el-dialog
      :title="$t('user.selectAirDrops')"
      :visible.sync="visible"
      width="50%"
      class="select-drop-dialog"
    >

      <el-form :inline="true" :model="searchForm" class="demo-form-inline form">
        <el-form-item>
          <div class="operation-bar">
            <div :class="[isBox == true?'default-btn':'default-btn primary-btn','default-btn']" @click="changeType(false)">{{ $t('home.goods') }}</div>
            <div :class="[isBox == true?'default-btn primary-btn':'default-btn','default-btn']" @click="changeType(true)">{{ $t('home.blindBox') }}</div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-input v-if="isBox == false"
            v-model="keyword"
            size="small"
            :placeholder="$t('user.airDropTip1')"
            clearable
          ></el-input>
          <el-input v-if="isBox == true"
            v-model="boxName"
            size="small"
            :placeholder="$t('user.airDropTip2')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div
            class="default-btn primary-btn"
            @click="searchChange"
          >{{ $t("pictureManager.query") }}
          </div>
        </el-form-item>
      </el-form>
      <div v-if="showProdDiv" class="main-container">
        <div class="prods-select-body table-con">
          <el-table
            ref="dropTable"
            :data="dataList"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            v-loading="dataListLoading"
            @selection-change="selectChangeHandle"
            style="width: 100%;"
          >
            <el-table-column v-if="isSingle" width="50">
              <template slot-scope="scope">
                <div>
                  <el-radio
                    :label="scope.row.prodId"
                    @change.native="getSelectProdRow(scope.row)"
                  >&nbsp;
                  </el-radio>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!isSingle"
              type="selection"
              width="50"
            ></el-table-column>
            <el-table-column
              fixed
              prop="prodName"
              :label="$t('group.prodInfo')"
              width="320">
              <template slot-scope="scope">
                <div class="table-cell-con">
                  <div class="table-cell-image">
                    <ImgShow :src="scope.row.pic"/>
                  </div>
                  <span class="table-cell-text">{{ scope.row.prodName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="oriPrice"
              :label="$t('prodList.marketValue')">
            </el-table-column>
            <el-table-column
              prop="price"
              :label="$t('prodList.salesPrice')">
            </el-table-column>
            <el-table-column
              prop="totalStocks"
              :label="$t('product.availableInventory')"
            ></el-table-column>
            <el-table-column
              align="center"
              :label="$t('user.perRecevies')"
            >
              <template slot="header">
                <span>{{ $t('user.perRecevies') }}</span>
                <el-popover
                  placement="top"
                  width="200"
                  trigger="hover"
                  :content="$t('user.couponTip2')"
                >
                  <i class="el-icon-question" slot="reference"></i>
                </el-popover>
              </template>
              <template slot-scope="scope">
                <el-input-number
                  size="mini"
                  v-model="scope.row.eachObtain"
                  controls-position="right"
                  @change="handleChange(scope.row,scope.$index)"
                  :min="scope.row.totalStocks>0?1:0"
                  :max=" scope.row.totalStocks>0?scope.row.totalStocks:0"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          v-if="dataList.length"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="page.pageIndex"
          :page-sizes="[5, 10, 25, 50]"
          :page-size="page.pageSize"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        <!-- <div v-if="tagList.length < 1">暂无数据</div> -->
      </div>
      <div v-if="showBoxDiv" class="main-container" >
        <div class="prods-select-body table-con">
          <el-table
            ref="dropBoxTable"
            :data="dataBoxList"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            v-loading="dataListLoading"
            @selection-change="selectBoxChangeHandle"
            style="width: 100%;"
          >
            <el-table-column v-if="isSingle" width="50">
              <template slot-scope="scope">
                <div>
                  <el-radio
                    :label="scope.row.id"
                    @change.native="getSelectBoxRow(scope.row)"
                  >&nbsp;
                  </el-radio>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!isSingle"
              type="selection"
              width="50"
            ></el-table-column>
            <el-table-column
              fixed
              prop="boxName"
              :label="$t('group.prodInfo')"
              width="320">
              <template slot-scope="scope">
                <div class="table-cell-con">
                  <div class="table-cell-image">
                    <ImgShow :src="scope.row.imgs"/>
                  </div>
                  <span class="table-cell-text">{{ scope.row.boxName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="price"
              :label="$t('prodList.salesPrice')">
            </el-table-column>
            <el-table-column
              prop="totalStocks"
              :label="$t('product.totalStocks')"
            ></el-table-column>
            <el-table-column
              align="center"
              :label="$t('user.perRecevies')"
            >
              <template slot="header">
                <span>{{ $t('user.perRecevies') }}</span>
                <el-popover
                  placement="top"
                  width="200"
                  trigger="hover"
                  :content="$t('user.couponTip2')"
                >
                  <i class="el-icon-question" slot="reference"></i>
                </el-popover>
              </template>
              <template slot-scope="scope">
                <el-input-number
                  size="mini"
                  v-model="scope.row.eachObtain"
                  controls-position="right"
                  @change="handleChange(scope.row,scope.$index)"
                  :min="scope.row.totalStocks>0?1:0"
                  :max=" scope.row.totalStocks>0?scope.row.totalStocks:0"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          v-if="dataBoxList.length"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="page.pageIndex"
          :page-sizes="[5, 10, 25, 50]"
          :page-size="page.pageSize"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
      <el-alert
        :title="this.$i18n.t('publics.sendDropTips')"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>
      <span slot="footer">
        <div @click="visible = false" class="default-btn">{{ $t('remindPop.cancel') }}</div>
        <div class="default-btn primary-btn" @click="submitProds()">{{ $t('remindPop.confirm') }}</div>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import {Debounce} from '@/utils/debounce'

export default {
  data () {
    return {
      visible: false,
      confirmLoad: false,
      dataForm: {
        userIds: [],
        drops: [],
        businessType: '0' // 空投业务类型 0：平台人工空投 1：店铺人工空投 2：任务空投
      },
      dataList: [], // 商品
      dataBoxList: [], // 盲盒
      dataRule: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 5 // 每页显示多少条
      },
      dataListLoading: false,
      searchForm: {},
      keyword: null,
      status: null,
      boxName: null,
      dataListSelections: [],
      showBoxDiv: false,
      showProdDiv: true,
      isBox: false
    }
  },
  components: {},
  props: {
    value: {
      default: '',
      type: String
    },
    // 获取方式 null:默认（客户领取+平台发放） 0=客户领取 1=平台发放
    getWay: {
      default: null,
      type: Number
    },
    isSingle: {
      default: false,
      type: Boolean
    },
    // 最大上传数量
    limit: {
      default: 9,
      type: Number
    }
  },
  mounted () {
  },
  methods: {
    init (ids) {
      this.isBox = false
      this.showProdDiv = true
      this.showBoxDiv = false
      this.visible = true
      this.dataForm.userIds = ids
      this.dataList = [] // 商品
      this.dataBoxList = [] // 盲盒
      this.getDataList()
    },
    // 每页数
    sizeChangeHandle (val) {
      this.page.pageSize = val
      this.page.currentPage = 1
      if (this.isBox) {
        this.getBoxDataList(this.page)
      } else {
        this.getDataList(this.page)
      }
    },
    // 当前页
    currentChangeHandle (val) {
      this.page.currentPage = val
      if (this.isBox) {
        this.getBoxDataList(this.page)
      } else {
        this.getDataList(this.page)
      }
    },
    changeType (val) {
      this.page = {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 5 // 每页显示多少条
      }
      this.searchForm = {}
      this.isBox = val
      this.visible = true
      if (val) {
        this.showBoxDiv = true
        this.showProdDiv = false
        this.dataList = [] // 商品
        this.dataBoxList = [] // 盲盒
        this.getBoxDataList()
      } else {
        this.dataList = [] // 商品
        this.dataBoxList = [] // 盲盒
        this.showBoxDiv = false
        this.showProdDiv = true
        this.getDataList()
      }
    },
    // 分页获取商品列表
    getDataList (page) {
      this.dataListLoading = true
      // 排除导入的外部商品数据
      this.searchForm.prodSource = 0
      this.$http({
        url: this.$http.adornUrl('/platform/search/prod/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              size: page == null ? this.page.pageSize : page.pageSize
            },
            this.searchForm
          )
        )
      }).then(({data}) => {
        this.dataList = data.records
        this.dataList.forEach(item => {
          this.$set(item, 'eachObtain', 1)
          this.$set(item, 'type', 0)
        })
        this.page.total = data.total
        this.dataListLoading = false
      })
    },
    // 分页获取盲盒列表
    getBoxDataList (page) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/activity/mysteryBox/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              size: page == null ? this.page.pageSize : page.pageSize
            },
            this.searchForm
          )
        )
      }).then(({data}) => {
        this.dataBoxList = data.records
        this.dataBoxList.forEach(item => {
          this.$set(item, 'eachObtain', 1)
          this.$set(item, 'type', 1)
        })
        this.page.total = data.total
        this.dataListLoading = false
      })
    },
    // 搜索
    searchChange () {
      if (this.isBox == false) {
        this.searchForm.keyword = this.keyword
        this.searchForm.status = this.status
        this.getDataList(this.page)
      } else {
        this.searchForm.boxName = this.boxName
        this.getBoxDataList(this.page)
      }
    },
    // 单选商品事件
    getSelectProdRow (row) {
      // console.log('aa')
      this.dataListSelections = [row]
    },
    // 单选盲盒事件
    getSelectBoxRow (row) {
      // console.log('aa')
      this.dataListSelections = [row]
    },
    // 多选
    // 多选商品点击事件
    selectChangeHandle (selection) {
      this.dataList.forEach((tableItem) => {
        let selectedProdIndex = selection.findIndex((selectedCoupon) => {
          if (!selectedCoupon) {
            this.dataListSelections = []
            return false
          }
          return selectedCoupon.prodId === tableItem.prodId
        })
        let dataSelectedProdIndex = this.dataListSelections.findIndex((dataSelectedCoupon) => dataSelectedCoupon.prodId === tableItem.prodId)
        if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
          this.dataListSelections.push(tableItem)
        } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
          this.dataListSelections.splice(dataSelectedProdIndex, 1)
        }
      })
    },
    // 多选
    // 多选盲盒点击事件
    selectBoxChangeHandle (selection) {
      this.dataBoxList.forEach((tableItem) => {
        let selectedProdIndex = selection.findIndex((selectedCoupon) => {
          if (!selectedCoupon) {
            this.dataListSelections = []
            return false
          }
          return selectedCoupon.id === tableItem.id
        })
        let dataSelectedProdIndex = this.dataListSelections.findIndex((dataSelectedCoupon) => dataSelectedCoupon.id === tableItem.id)
        if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
          this.dataListSelections.push(tableItem)
        } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
          this.dataListSelections.splice(dataSelectedProdIndex, 1)
        }
      })
    },
    // 确定事件
    submitProds () {
      // 商品单选的情况
      if (this.isSingle) {
        this.dataListSelections.length && this.$emit('refreshSelectCouponList', this.dataListSelections[0])
        this.dataListSelections = []
        this.visible = false
        return
      }
      // 多选
      let drops = []
      if (this.dataListSelections.length < 1) {
      } else {
        this.dataListSelections.forEach(item => {
          if (this.isBox) {
            let prodIndex = drops.findIndex((drop) => drop.id === item.id)
            if (prodIndex === -1) {
              drops.push({
                targetId: item.id,
                nums: item.eachObtain,
                type: item.type
              })
            }
          } else {
            let prodIndex = drops.findIndex((drop) => drop.prodId === item.prodId)
            if (prodIndex === -1) {
              drops.push({
                targetId: item.prodId,
                nums: item.eachObtain,
                type: item.type
              })
            }
          }
        })
      }
      this.dataForm.drops = drops
      this.dataListSelections = []
      this.confirm()
    },
    confirm: Debounce(function () {
      if (!this.dataForm.userIds) {
        return
      }
      if (!this.dataForm.drops || !this.dataForm.drops.length) {
        return this.$message.error(this.$t('coupon.pleaseSelectDrop'))
      }
      this.confirmLoad = true
      let drops = []
      this.dataForm.drops.forEach(element => {
        let obj = {}
        obj.targetId = element.targetId
        obj.nums = element.nums
        obj.type = element.type
        drops.push(obj)
      })
      this.dataForm.drops = drops
      let param = this.dataForm
      console.log(param)
      this.$http({
        url: this.$http.adornUrl(`/platform/airdrop/sendUserDrop`),
        method: 'put',
        data: this.$http.adornData(param)
      }).then(({data}) => {
        this.active = []
        this.$message({
          message: this.$i18n.t('remindPop.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.confirmLoad = false
            this.isBox = false
            this.showBoxDiv = false
            this.showProdDiv = true
            this.$emit('refreshDataList', this.page)
          }
        })
      }).catch((e) => {
      })
    }, 1000),
    handleChange (row, index) {
      this.$set(this.dataList, index, this.dataList[index])
    }
  }
}
</script>
<style lang="scss" scoped>
.active {
  float: left;
  margin-left: 10px;
  padding: 10px;
  background: #e6a23c;
  margin-bottom: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.Classification {
  float: left;
  margin-left: 10px;
  padding: 10px;
  background: #f7f7f7;
  margin-bottom: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.select-drop-dialog {
  .el-form-item {
    margin-bottom: 0;
  }

  .el-input.el-input--small {
    width: 200px;
  }

  .main-container {
    margin-bottom: 20px;
  }
}
</style>
